package org.example.Controller;

import lombok.extern.slf4j.Slf4j;
import org.example.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    String basePath;

    /**
     * 上传图片资源
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //file 是一个临时文件，如果不转存，则请求完成后会自动删除
        log.info("文件上传upload：{}",file);


        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName =UUID.randomUUID() + suffix;

        //目录不存在则先创建
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        log.info("文件上传地址{}",basePath+fileName);
        file.transferTo(new File(basePath+fileName));
        return R.success(fileName);
    }

    /**
     * 下载图片资源
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(basePath+name))){
            response.setContentType("image/*");

            byte[] bytes = new byte[1024];
            int len;
            while((len = inputStream.read(bytes))!=-1){
                response.getOutputStream().write(bytes,0,len);
                response.getOutputStream().flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
